package com.gokzzz.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.gokzzz.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用
 *
 * @author ganfujia
 * @date 2022/3/15 15:56
 */
@Component
@Slf4j
public class MetaHandler implements MetaObjectHandler {

    /**
     * 新增数据执行
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        String username = null;
        try {
            username = SecurityUtil.getCurrentUsername();
        }catch (Exception e){
            username = "system";
        }
        this.setFieldValByName("createBy", username, metaObject);
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", username, metaObject);
    }

    /**
     * 更新数据执行
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        String username = null;
        try {
            username = SecurityUtil.getCurrentUsername();
        }catch (Exception e){
            username = "system";
        }
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", username, metaObject);
    }
}
